package com.googlecode.sftpant;

import java.util.ArrayList;

import me.kolovos.sftpant.CdCommand;
import me.kolovos.sftpant.LsCommand;
import me.kolovos.sftpant.MkDirCommand;
import me.kolovos.sftpant.PutCommand;
import me.kolovos.sftpant.RenameCommand;
import me.kolovos.sftpant.RmCommand;
import me.kolovos.sftpant.RmDirCommand;
import me.kolovos.sftpant.SftpCommand;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class SftpTask extends Task {
	
	protected String server;
	protected String username;
	protected String password;
	protected int port = 22;
	protected boolean strictHostKeyChecking = false;
	protected ChannelSftp channel;
	protected ArrayList<SftpCommand> commands = new ArrayList<SftpCommand>();
	
	public void execute() throws BuildException {
		try {
			executeImpl();
		}
		catch (Exception ex) {
			throw new BuildException(ex);
		}
	}
	
	public void executeImpl() throws Exception {
		
		
		JSch jsch = new JSch();
		Session session = jsch.getSession(username, server);
		if (!strictHostKeyChecking) {
			session.setConfig("StrictHostKeyChecking", "no");
		}
		session.setPassword(password);
		session.connect();
		Channel channel = session.openChannel( "sftp" );
		channel.connect();

		this.channel = (ChannelSftp) channel;
		
		for (SftpCommand command : commands) {
			command.setChannel(this.channel);
			command.execute();
		}
		
		this.channel.disconnect();
		session.disconnect();
	}
	
	public void addPut(PutCommand command) {
		commands.add(command);
	}
	
	public void addLs(LsCommand command) {
		commands.add(command);
	}
	
	public void addCd(CdCommand command) {
		commands.add(command);
	}
	
	public void addRename(RenameCommand command) {
		commands.add(command);
	}
	
	public void addMkDir(MkDirCommand command) {
		commands.add(command);
	}
	
	public void addRm(RmCommand command) {
		commands.add(command);
	}
	
	public void addRmDir(RmDirCommand command) {
		commands.add(command);
	}
	
	public String getServer() {
		return server;
	}

	public void setServer(String server) {
		this.server = server;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public boolean isStrictHostKeyChecking() {
		return strictHostKeyChecking;
	}

	public void setStrictHostKeyChecking(boolean strictHostKeyChecking) {
		this.strictHostKeyChecking = strictHostKeyChecking;
	}
	
	
	
}
